﻿#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

typedef int SLDataType;
// 动态顺序表 -- 按需申请
typedef struct SqeList
{
	SLDataType* arr;
	int size; // 有效数据个数
	int CapaCity; // 容量
}SL;

//初始化
void SLInit(SL* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->size = ps->CapaCity = 0;
}

//销毁
void SLDestroy(SL* ps)
{
	assert(ps);
	if (ps->arr)
	{
		free(ps->arr);
	}
	ps->size = ps->CapaCity = 0;
}

//打印
void SLPrint(SL* ps)
{
	assert(ps);
	if (ps->size)
	{
		for (int i = 0; i < ps->size; i++)
		{
			printf("%d ", ps->arr[i]);
		}
		printf("\n");
	}
}

//扩容
void SLCheckCapaCity(SL* ps)
{
	assert(ps);
	if (ps->size == ps->CapaCity)
	{
		int NewCapaCity = ps->CapaCity == 0 ? 4 : ps->CapaCity * 2;
		SLDataType* NewArr = (SLDataType*)realloc(ps->arr, NewCapaCity * sizeof(SLDataType));
		if (NewArr == NULL)
		{
			perror("realloc fail");
			exit(1);
		}
		ps->arr = NewArr;
		ps->CapaCity = NewCapaCity;
	}
}

//尾插
void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapaCity(ps);
	ps->arr[ps->size++] = x;
}

//尾删
void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);
	ps->size--;
}

//头插
void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapaCity(ps);
	for (int i = ps->size; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	ps->size++;
}

//头删
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);
	for (int i = 0; i < ps->size - 1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

//指定位置之前插⼊
void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	SLCheckCapaCity(ps);
	for (int i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	ps->size++;
}

//删除指定位置数据
void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(ps->size > 0);
	assert(pos >= 0 && pos < ps->size);
	for (int i = pos; i < ps->size - 1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

//查找指定位置数据，返回下标
int SLFind(SL* ps, SLDataType x)
{
	assert(ps);
	assert(ps->size > 0);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
		{
			return i;
		}
	}
	return -1;
}

int main()
{
	SL s;

	SLInit(&s);

	SLPushBack(&s, 1);
	SLPushBack(&s, 2);
	SLPushBack(&s, 3);
	SLPushBack(&s, 4);
	SLPushBack(&s, 5);

	SLPrint(&s);

	SLPopBack(&s);
	SLPopBack(&s);

	SLPrint(&s);

	SLPushFront(&s, 6);
	SLPushFront(&s, 7);
	SLPushFront(&s, 8);

	SLPrint(&s);

	SLPopFront(&s);
	SLPopFront(&s);

	SLPrint(&s);

	SLInsert(&s, 3, 9);

	SLPrint(&s);

	SLErase(&s, 1);

	SLPrint(&s);

	int ret = SLFind(&s, 2);
	if (ret == -1)
	{
		printf("没有找到\n");
	}
	else
	{
		printf("找到了，下标是：%d\n", ret);
	}

	SLDestroy(&s);

	return 0;
}